package cn.edu.ctbu.lastwork.demos.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import cn.edu.ctbu.lastwork.demos.web.entity.Grade;
import cn.edu.ctbu.lastwork.demos.web.repository.GradeRepository;
import cn.edu.ctbu.lastwork.demos.web.repository.StudentRepository;

@Controller
@RequestMapping("/grades")
public class GradeController {
    @Autowired
    private GradeRepository gradeRepository;
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping
    public String listGrades(Model model) {
        model.addAttribute("grades", gradeRepository.findAll());
        return "grades";
    }

    @GetMapping("/new")
    public String newGradeForm(Model model) {
        model.addAttribute("grade", new Grade());
        model.addAttribute("students", studentRepository.findAll());
        return "grade-form";
    }

    @PostMapping
    public String saveGrade(@ModelAttribute Grade grade) {
        gradeRepository.save(grade);
        return "redirect:/grades";
    }
}
